package org.vin.tempctl;

import java.net.InetAddress;

import com.intelligt.modbus.jlibmodbus.Modbus;
import com.intelligt.modbus.jlibmodbus.exception.ModbusIOException;
import com.intelligt.modbus.jlibmodbus.master.ModbusMaster;
import com.intelligt.modbus.jlibmodbus.master.ModbusMasterFactory;
import com.intelligt.modbus.jlibmodbus.tcp.TcpParameters;

/**
 * modbus通讯，使用jlibmodbus，实现功能码04
 *
 */
public class JLibModbusDemo {

    public static void main(String[] args) {
        try {
            // 设置主机TCP参数
            TcpParameters tcpParameters = new TcpParameters();
            // 设置TCP的ip地址
            InetAddress adress = InetAddress.getByName("127.0.0.1");
            // TCP参数设置ip地址
            // tcpParameters.setHost(InetAddress.getLocalHost());
            tcpParameters.setHost(adress);
            // TCP设置长连接
            tcpParameters.setKeepAlive(true);
            // TCP设置端口，这里设置是默认端口502
            tcpParameters.setPort(Modbus.TCP_PORT);
            // 创建一个主机
            ModbusMaster master = ModbusMasterFactory.createModbusMasterTCP(tcpParameters);
            Modbus.setAutoIncrementTransactionId(true);
            if (!master.isConnected()) {
                master.connect();// 开启连接
            }

            try {
                // --//------------------
                boolean flag = Temperature.setTemperature(50, master);
                // --//------------------
                System.out.println("setTemperatureflag ---> "+flag);
                // --//-----------------
                int tem = Temperature.getTemperature( master);
                System.out.println("getTemperatureflag ---> "+tem);

                //flag = Temperature.setTemrate(10, master);
                //System.out.println("setTemrateflag ---> "+flag);

                boolean ret = Temperature.seton( master);
                System.out.println("setoret ---> "+ret);

                ret = Temperature.setoff( master);
                System.out.println("setoffret ---> "+ret);

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    master.disconnect();
                } catch (ModbusIOException e) {
                    e.printStackTrace();
                }
            }

        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
